#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <mysql/mysql.h>

int main()
{
  //1. 初始化句柄
  MYSQL* mysql = mysql_init(NULL);//通常传参传NULL
  if(mysql == NULL){
    printf("mysql init error\n");
    return -1;
  }
  //2. 连接数据库服务器
  if(mysql_real_connect(mysql, "192.168.197.128", "root", NULL, "test", 0, NULL, 0) == NULL){ //root用户无密码。使用test库
    printf("connect mysql server failed! : %s\n", mysql_error(mysql));
    mysql_close(mysql);
    return -1;
  }
  //3. 设置字符集
  int ret;
  ret = mysql_set_character_set(mysql, "utf8");
  if(ret != 0){
     printf("set character failed! : %s\n", mysql_error(mysql));
     mysql_close(mysql);
     return -1;
  }
  //4. 选择要操作的库 mysql_select_db(mysql, "test"); 就不做修改了，用上面的库
  //5. 执行语句
  //  const char* insert = "insert student values(3, '宇航', 21, now());";
  //  const char* insert = "update student set name='刘老三' where sn = 3;";
  //  const char* insert = "delete from student;";
  const char* select_sql = "select * from student;";
  ret = mysql_query(mysql,select_sql);
  if(ret != 0){
    printf("query sql failed! : %s\n", mysql_error(mysql));
    mysql_close(mysql); 
    return -1;
  }
  //6. 如果是查询语句则获取查询结果
  MYSQL_RES* res = mysql_store_result(mysql);
  if(res == NULL){
    printf("store result failed! : %s\n", mysql_error(mysql));
    mysql_close(mysql);
    return -1; 
  }

  int num_row = mysql_num_rows(res);
  int num_col = mysql_num_fields(res);
  for(int i = 0; i < num_row; ++i){
    MYSQL_ROW row = mysql_fetch_row(res);
    for(int j = 0; j < num_col; ++j){
      printf("%-15s",row[j]);
    }
    printf("\n");
  }
  //6.99 释放结果集
  mysql_free_result(res);
  //7. 关闭句柄
  mysql_close(mysql);
  return 0;

}
